package com.uetoken.cn.activity;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.uetoken.cn.R;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.CountDownTimerUtils;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author 谢杨
 * 用户信息修改界面(修改昵称或输入旧手机号页面)
 */
public class ModifyUserInfoActivity extends BaseActivity implements WebResponse {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.edt_activity_modify_user_info_nickname)
    EditText mEdtModifyNickname;
    @BindView(R.id.iv_activity_modify_user_info_confirm_modify)
    ImageView mIvConfirmModify;
    @BindView(R.id.ll_activity_modify_user_info_modify_nickname)
    LinearLayout mLlModifyNickname;
    @BindView(R.id.edt_activity_modify_user_info_phone_number)
    EditText mEdtModifyPhoneNumber;
    @BindView(R.id.tv_activity_modify_user_info_get_verification_code)
    TextView mTvActGetVerificationCode;
    @BindView(R.id.edt_activity_modify_user_info_please_input_verification_code)
    EditText mEdtInputVerificationCode;
    @BindView(R.id.ll_activity_modify_user_info_modify_phone)
    LinearLayout mLlModifyPhone;
    @BindView(R.id.tv_activity_modify_user_info_confirm_modify)
    TextView mTvUserInfoConfirmModify;
    @BindView(R.id.iv_activity_modify_user_info_confirm_modify_bnt)
    Button mBtnConfirmModify;
    public static final String MODIFY_USER_INFO = "modify_user_info";
    /**
     * 获取验证码的请求码
     */
    private static final int NETWORK_REQUEST_GET_CODE = 10;
    /**
     * 修改昵称的请求码
     */
    private static final int NETWORK_REQUEST_MODIFY_NICKNAME = 20;

    /**
     * 从用户昵称点击跳过来的flag
     */
    private static final int INTENT_NICKNAME_FLAG = 1;
    /**
     * 从手机号码点击跳过来的flag
     */
    private static final int INTENT_PHONE_FLAG = 2;
    /**
     * 跳转标识
     */
    private int flag;
    /**
     * 倒计时器
     */
    private CountDownTimerUtils countDownTimerUtils;

    @Override
    public int getLayoutId() {
        return R.layout.activity_modify_user_info;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);

        //状态栏沉浸式
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, android.R.color.white), true);
        BarUtils.setStatusBarLightMode(this, true);

        mIvBack.setVisibility(View.VISIBLE);

        setEditTextInhibitInputSpeChat(mEdtModifyNickname);
    }


    /**
     * 禁止EditText输入特殊字符
     *
     * @param editText
     */
    private void setEditTextInhibitInputSpeChat(EditText editText) {

        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String speChat = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if (matcher.find()) return "";
                else return null;
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }


    @Override
    public void initData() {
        flag = getIntent().getIntExtra(MODIFY_USER_INFO, 0);
        if (INTENT_NICKNAME_FLAG == flag) {
            mTvTitle.setText(getResources().getString(R.string.str_modify_nickname));
            mTvUserInfoConfirmModify.setVisibility(View.GONE);
            mLlModifyPhone.setVisibility(View.GONE);
            mEdtModifyNickname.setText(getIntent().getStringExtra("nickname"));
            //设置焦点在最后面
            mEdtModifyNickname.setSelection(mEdtModifyNickname.getText().toString().length());
        } else if (INTENT_PHONE_FLAG == flag) {
            mTvTitle.setText(getResources().getString(R.string.str_auth_original_phone));
            String mobile = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_MOBILE_NO, "");
            mEdtModifyPhoneNumber.setText(mobile);
            mLlModifyNickname.setVisibility(View.GONE);
            mTvUserInfoConfirmModify.setText(getResources().getString(R.string.str_next));
        }
    }

    @Override
    public void init() {

    }


    @OnClick({R.id.iv_back, R.id.iv_activity_modify_user_info_confirm_modify_bnt, R.id.tv_activity_modify_user_info_get_verification_code, R.id
            .tv_activity_modify_user_info_confirm_modify})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_activity_modify_user_info_confirm_modify_bnt:
                modifyNickname();
                break;
            case R.id.tv_activity_modify_user_info_get_verification_code:
                getVerificationCode();
                break;
            case R.id.tv_activity_modify_user_info_confirm_modify:
                String phone = mEdtModifyPhoneNumber.getText().toString().trim();
                String code = mEdtInputVerificationCode.getText().toString().trim();

                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.showShort(getResources().getString(R.string.str_phone_not_be_empty));
                    return;
                }
                if (!RegexUtils.isMobileSimple(phone)) {
                    ToastUtils.showShort(getResources().getString(R.string.str_phone_not_specification));
                    return;
                }
                if (TextUtils.isEmpty(code)) {
                    ToastUtils.showShort(getResources().getString(R.string.str_auth_code_not_empty));
                    return;
                }
                Intent intent = new Intent(this, InputNewPhoneActivity.class);
                intent.putExtra("phone", phone);
                intent.putExtra("code", code);
                startActivity(intent);
                break;
        }
    }

    /**
     * 修改昵称
     */
    private void modifyNickname() {
        String nickName = mEdtModifyNickname.getText().toString().trim();
        if (TextUtils.isEmpty(nickName)) {
            ToastUtils.showShort("");
            return;
        }
        if (nickName.length() < 2) {
            ToastUtils.showShort(getResources().getString(R.string.str_nickname_not_specification));
            return;
        }
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getModifyUserInfoUrl(), NETWORK_REQUEST_MODIFY_NICKNAME,
                Params.getModifyUserInfoParams("1", nickName, ""));
    }

    /**
     * 获取验证码
     */
    private void getVerificationCode() {
        String phone = mEdtModifyPhoneNumber.getText().toString().trim();

        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_be_empty));
            return;
        }
        if (!RegexUtils.isMobileSimple(phone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_specification));
            return;
        }
        countDownTimerUtils = new CountDownTimerUtils(this, mTvActGetVerificationCode, 60000, 1000);
        countDownTimerUtils.start();
        //调用接口获取验证码
        OkHttpUtils.getInstance().getStringWithParam(ModifyUserInfoActivity.this, ApiHelper.getSendSMSUrl(), NETWORK_REQUEST_GET_CODE, Params.getSmsParams(phone));
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        if (requestCode == NETWORK_REQUEST_GET_CODE) {

        } else if (requestCode == NETWORK_REQUEST_MODIFY_NICKNAME) {
            dissmissDialog();
            JsonObject obj = new JsonParser().parse(response).getAsJsonObject();
            int result = obj.get("result").getAsInt();
            String message = obj.get("message").getAsString();
            if (result > 0) {
                String nickName = mEdtModifyNickname.getText().toString();
                //修改昵称成功后将修改后的昵称保存在本地
                SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_NAME, nickName);

                //通知主activity刷新界面
                Intent successIntent = new Intent();
                successIntent.setAction("paySuccess");
                sendBroadcast(successIntent);

                ToastUtils.showShort(message);
                Intent intent = new Intent();
                intent.putExtra("nickname", nickName);
                setResult(RESULT_OK, intent);
                finish();
            } else {
                ToastUtils.showShort(message);
            }
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimerUtils != null) {
            countDownTimerUtils.cancel();
        }
    }
}
